package com.demo.sso.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.demo.sso.common.enums.IMsgEnum;
import com.demo.sso.enity.UserDO;
import com.demo.sso.reids.RedisManager;
import com.demo.sso.resp.BaseMsgResp;
import com.demo.sso.service.LoginService;
import com.demo.sso.service.UserService;
import com.demo.sso.util.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请添加模块注释
 *
 * @author fengjy
 * @date 2018-10-28 23:08
 */
public class LoginServiceImpl implements LoginService{

    @Autowired
    private UserService userService;

    @Autowired
    private RedisManager redisManager;

    @Override
    public BaseMsgResp login(String username, String password) throws AuthenticationException {
        BaseMsgResp resp = new BaseMsgResp();
        password = MD5Utils.encrypt(password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        //获取用户
        Map<String, Object> params = new HashMap<>();
        params.put("username", username);
        List<UserDO> list = userService.list(params);
        if(list.size() > 1) {
            resp = new BaseMsgResp(IMsgEnum.SYSTEM_ANOMALY.getMsgCode(), IMsgEnum.SYSTEM_ANOMALY.getMsgText());
            return resp;
        }
        //token
        Serializable id = subject.getSession().getId();
        //将token放入redis
        redisManager.set("sys:login:user_token_"+id.toString(),list.get(0).getUserId()+"",60*30);
        //防止同一个账号同时登录
        redisManager.set("sys:user:id_"+list.get(0).getUserId(), id.toString(),60*30);
        //用户信息
        redisManager.set("sys:login:user_info_"+list.get(0).getUserId(), JSONObject.toJSONString(list.get(0)),60*30);
        return resp;
    }
}
